import React from 'react';
import { Link } from 'react-router-dom';
import { Card, message } from 'antd';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';

import NewsList from '../store/new_list'

@inject((stores) => {
  const store = {
    newsList: stores.newsList,
  }
  return store
})
@observer
class PCNewsModule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      news: '',
    }
  }
  componentDidMount() {
    this.getNews();
  }
  componentDidUpdate(preProps) {
    // 更新前后的type不一样,重新获取数据
    if (preProps.type !== this.props.type) { this.getNews(); }
  }
  componentWillUnmount() {
    this.props.newsList.deleteListNews(this.props.type)
  }
  // 获取新闻
  getNews() {
    // 获取新参数，channel和num
    const { type, count } = this.props;
    this.props.newsList.getListNews(type, count).catch(e => message.error(`获取新闻失败，请稍后再试 ${e}`))
  }
  getNewsDataFromBobx() {
    let news = []
    const channel = decodeURIComponent(this.props.type) //eslint-disable-line
    const { newsListData } = this.props.newsList
    news = !!newsListData.get(channel) ? newsListData.get(channel).data : [] // eslint-disable-line
    return news
  }
  asyncBootstrap() {
    return new Promise((resolve) => {
      const { type, count } = this.props;
      this.props.newsList.getListNews(type, count)
        .then(() => resolve(true))
    })
  }
  render() {
    const news = this.getNewsDataFromBobx()
    return (
      <div className="news-module">
        <Card title={this.props.title}>
          <ul className="news-list">
            { news.length ?
              news.map(newsItem => (
                <li key={newsItem.id} >
                  <Link to={`/detail/${newsItem.id}`}>{newsItem.title}</Link>
                </li>
              )) : <div className="loading">加载中...</div>
            }
          </ul>
        </Card>
      </div>
    )
  }
}
export default PCNewsModule;

PCNewsModule.propTypes = {
  type: PropTypes.string.isRequired,
  count: PropTypes.string,
  title: PropTypes.string,
  newsList: PropTypes.instanceOf(NewsList),
}
